package cn.hnucm.service;

import cn.hncum.feign.clients.EsClient;
import cn.hncum.feign.clients.EsOrderClient;
import cn.hncum.feign.clients.UserClient;
import cn.hnucm.bean.TbCapital;
import cn.hnucm.bean.TbGoodsBasis;
import cn.hnucm.bean.TbGoodsOrder;
import cn.hnucm.bean.TbUserBasis;
import cn.hnucm.pojo.User;
import cn.hnucm.vo.AddOrder;
import cn.hnucm.vo.Goods;
import cn.hnucm.vo.ReturnOrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author:liweihua
 * @Description:
 * @Date: 21:31$ 2021/12/28/028$
 * @Modified:
 */
@Service("esControllerService")
public class EsControllerService extends AbstractCenterControllerService{
    @Autowired
    EsClient esClient;
    @Autowired
    EsOrderClient esOrderClient;
    @Autowired
    UserClient userClient;

    private User user;

    private Goods goods;

    private String ip;
    @Override
    public void setUser() {
        List<TbUserBasis> userBasisById = userClient.getUserBasisById(goods.getUserId()+"",this.ip, goods.getUserId());
        User user1 = new User();
        user1.setUserPassword(userBasisById.get(0).getUserPayPassword());
        user1.setAsset(userBasisById.get(0).getUserAsset());
        user1.setId(goods.getUserId());
        this.user = user1;
    }

    @Override
    public void setGoods(Goods goods) {
        this.goods = goods;
    }

    @Override
    public boolean matchPassword() {
        if(goods.getUserPassword().equals(user.getUserPassword())){
            return true;
        }
        return false;
    }

    @Override
    public boolean verifyBalance() {
        try {
            TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(goods.getGoodId());
            float goodsPrice = tbGoodsBasis.getGoodsPrice();
            float allMoney = goods.getNum() * goodsPrice;
            if(user.getAsset() >= allMoney){
                return true;
            }
            return false;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateGoods() {
        try {
            TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(goods.getGoodId());
            if(tbGoodsBasis.getGoodsStock() >= goods.getNum()){
                int excess = tbGoodsBasis.getGoodsStock() - goods.getNum();
                boolean b = esClient.updateGoodsNumById(goods.getGoodId(), excess);
                return b;
            }else{
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public boolean rollbackUpdateGoods() {
        TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(goods.getGoodId());
        int excess = tbGoodsBasis.getGoodsStock() + goods.getNum();
        boolean b = esClient.updateGoodsNumById(goods.getGoodId(), excess);
        return b;
    }

    @Override
    public TbGoodsOrder UpdateOrder() {
        try {
            TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(goods.getGoodId());
            float orderInvoleValue = tbGoodsBasis.getGoodsPrice() * goods.getNum();
            AddOrder addOrder = new AddOrder();
            addOrder.setBuyerId(user.getId());
            addOrder.setOrderInvoleValue(orderInvoleValue);
            addOrder.setGoodsId(goods.getGoodId());
            addOrder.setSellerId(tbGoodsBasis.getGoodsOwerId());
            addOrder.setGoodsNum(goods.getNum());
            TbGoodsOrder tbGoodsOrder = esOrderClient.addOrder(addOrder);
            return tbGoodsOrder;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean rollbackUpdateOrder(int orderId) {
        return false;
    }

    @Override
    public boolean updateUserBalance() {
        try {
            TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(goods.getGoodId());
            float balance = user.getAsset() - (tbGoodsBasis.getGoodsPrice() * goods.getNum());
            boolean b = userClient.updateUserBalanceById(user.getId(), balance);
            return b;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public boolean rollbackUserBalance() {
        return false;
    }

    /**
     *
     *
     * @return
     * 0 密码错误
     * 1 购买成功
     * 2 余额不足
     * 3 商品库存不足
     * 4 网络异常
     */
    @Override
    public ReturnOrderInfo purchase(Goods goods,String ip) {
        System.out.println(goods.getGoodId());
        this.goods = goods;
        this.ip = ip;
        this.setUser();
        ReturnOrderInfo orderInfo = new ReturnOrderInfo();
        if(this.matchPassword()){
            if(this.verifyBalance()){
                if(this.updateGoods()){
                    TbGoodsOrder tbGoodsOrder = this.UpdateOrder();
                    if(tbGoodsOrder!=null){
                        if(this.updateUserBalance()){
                            //一切都成功
                            List<TbUserBasis> userBasisById = userClient.getUserBasisById(user.getId()+"",this.ip, user.getId());
                            TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(goods.getGoodId());
                            orderInfo.initReturnOrderInfo(tbGoodsOrder,userBasisById.get(0),tbGoodsBasis);
                            System.out.println("更新成功");
                            orderInfo.setMsg("订单生成成功！！");
                            return orderInfo;
                        }else{
                            this.rollbackUpdateGoods();
                            this.rollbackUpdateOrder(tbGoodsOrder.getOrderId());
                            orderInfo.setMsg("用户资金不足或存在异常");
                            System.out.println("更新用户资金失败");
                            return orderInfo;
                        }
                    }else{
                        //更新订单失败,回滚更新的商品数量
                        this.rollbackUpdateGoods();
                        System.out.println("更新订单失败");
                        orderInfo.setMsg("订单生成失败！");
                        return orderInfo;
                    }
                }else{
                    //更新商品数量失败，可能商品余额不足
                    System.out.println("更新商品数量失败");
                    orderInfo.setMsg("商品数量不足！");
                    return orderInfo;
                }
            }else{
                orderInfo.setMsg("用户资金不足！");
                return orderInfo;
            }
        }else{
            orderInfo.setMsg("用户密码不正确！");
            return orderInfo;
        }
    }

    @Override
    public ReturnOrderInfo confirm(int id,String ip) {
        ReturnOrderInfo orderInfo = new ReturnOrderInfo();
        try {
            TbGoodsOrder orderById = esOrderClient.getOrderById(id);
            boolean b = userClient.updateUserBalanceById(orderById.getSellerId(), orderById.getOrderInvoleValue());
            if(b){
                List<TbUserBasis> userBasisById = userClient.getUserBasisById(orderById.getBuyerId()+"",ip, orderById.getBuyerId());
                TbGoodsBasis tbGoodsBasis = esClient.getTbGoodsBasisByGoodsId(orderById.getGoodsId());
                TbGoodsOrder tbGoodsOrder = esOrderClient.finishOrderById(id);
                orderInfo.initReturnOrderInfo(tbGoodsOrder,userBasisById.get(0),tbGoodsBasis);
                TbCapital tbCapital = new TbCapital();
                tbCapital.setFromuserId(orderById.getBuyerId());
                tbCapital.setTouserId(orderById.getSellerId());
                tbCapital.setAmount(orderById.getOrderInvoleValue());
                Boolean capital = esOrderClient.createCapital(tbCapital);
                if(capital)
                    orderInfo.setMsg("更新订单成功，订单已完成");
                else
                    orderInfo.setMsg("更新订单成功，转账失败");
                return orderInfo;
            }
            orderInfo.setMsg("更新订单失败，请检查数据");
            return orderInfo;
        }catch (Exception e){
            orderInfo.setMsg("更新订单失败，请检查数据");
            e.printStackTrace();
            return orderInfo;
        }

    }

    @Override
    public int unConfirm(int id,String ip) {
        TbGoodsOrder orderById = esOrderClient.getOrderById(id);
        List<TbUserBasis> userBasisById = userClient.getUserBasisById(orderById.getBuyerId() + "", ip, orderById.getBuyerId());
        boolean b = userClient.updateUserBalanceById(orderById.getBuyerId(), orderById.getOrderInvoleValue()+userBasisById.get(0).getUserAsset());
        if(b){
            return 1;
        }
        return 0;
    }
}
